package utils

import (
	"mime/multipart"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// 保存上传的文件
func SaveUploadedFile(c *gin.Context, file *multipart.FileHeader, drive string, name string) (string, error) {
	switch drive {
	case "local":
		return saveFileLocal(c, file, name)
	default:
		return saveFileLocal(c, file, name)
	}
}

// 保存文件到本地
func saveFileLocal(c *gin.Context, file *multipart.FileHeader, name string) (string, error) {
	var pa string
	pa = time.Now().Format("20060102") + "/"
	if name == "" {
		name = strconv.Itoa(int(time.Now().UnixMilli()))
	}
	pa = "uploads/" + pa + name + path.Ext(file.Filename)
	if err := c.SaveUploadedFile(file, pa); err != nil {
		return "", err
	}
	return "/" + pa, nil
}

func DeleteFile(path string) (err error) {
	path = strings.TrimLeft(path, "/")
	err = os.Remove(path)
	if pa := filepath.Dir(path); pa != "." {
		err = DeleteFile(filepath.Dir(pa))
	}
	return
}
